package com.quyeying.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @ClassName JwtUtil
 * @Description TODO
 * @Author skx
 * @Date 2020/11/26
 */
@Configuration
public class JwtUtil {
    /**
     * 过期时间30分钟
     */
//    private static final long EXPIRE_TIME = 60000;
    private static final long EXPIRE_TIME = 1800000L;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "a347fe2b0661f1569fd4237320a110d3";

    /**
     * 生成签名,30分钟后过期
     * @param username
     * @return
     */
    public static String sign(String username){
        //过期时间
        long currentTimeMillis = System.currentTimeMillis() + EXPIRE_TIME;
        System.out.println(System.currentTimeMillis());
        Date date = new Date(currentTimeMillis);
        System.out.println(date.getTime());
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        return JWT.create().withHeader(header).withClaim("loginName",username)
                .withExpiresAt(date).sign(algorithm);
    }


    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean verity(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } catch (JWTVerificationException e) {
            System.out.println("过期的token");
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("loginName").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }
}
